﻿using BaseData.Domain;
using Microsoft.EntityFrameworkCore;

namespace BaseData.Infrastructure
{
    public class BaseDbContext : DbContext
    {
        public BaseDbContext(DbContextOptions options) : base(options)
        {
        }
        public DbSet<ApprovalNlog> ApprovalNlogs { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<ApprovalNlog>(eneity =>
            {
                eneity.Property(e=>e.ApprovalType).IsRequired().HasMaxLength(20);
                eneity.Property(e=>e.ApprovalLogDate).IsRequired();
                eneity.Property(e=>e.ApprovalLogName).IsRequired();
                eneity.Property(x=>x.BusinessNo).IsRequired();
            });
            //modelBuilder.Entity<Usertinfo>().HasQueryFilter(x => x.IsDel == false);
            //base.OnModelCreating(modelBuilder);
            // 自动为所有继承自 Basedata 的实体加上 IsDelete == false 的全局过滤器
            foreach (var entityType in modelBuilder.Model.GetEntityTypes())
                // 判断是否继承自 Basedata，且不是抽象类
                if
                (typeof(BaseEneity).IsAssignableFrom(entityType.ClrType) && !entityType.ClrType.IsAbstract)
                {
                    //构建表达式x=>!x.IsDelete
                    //创建一个参数 x，类型为当前实体类型(如 User、Role 等)。
                    var parameter = System.Linq.Expressions.Expression.Parameter(entityType.ClrType,
                    "x");
                    //获取当前实体类型的 IsDelete 属性。
                    var property = System.Linq.Expressions.Expression.Property(parameter, nameof
                    (BaseEneity.IsDeleted));
                    //创建一个表达式，表示 IsDelete 属性等于 false。
                    var compare = System.Linq.Expressions.Expression.Equal(property,
                    System.Linq.Expressions.Expression.Constant(false));
                    //创建一个 Lambda 表达式，表示x=>!x.IsDelete。
                    var lambda = System.Linq.Expressions.Expression.Lambda(compare,
                    parameter);
                    //将这个 Lambda 表达式作为査询过滤器应用到当前实体类型上。
                    entityType.SetQueryFilter(lambda);
                }
        }
        public DbSet<Depts> Depts { get; set; }
        public DbSet<LoginNlog> LoginNlogs { get; set; }
        public DbSet<MeetingTemplate> MeetingTemplates { get; set; }
        public DbSet<MettingRoom> MettingRooms { get; set; }
        public DbSet<MettingBooking> MettingBooking { get; set; }
        public DbSet<MettingRoomAddress> MettingRoomAddress { get; set; }
        public DbSet<OperatorNlog> OperatorNlog { get; set; }
        public DbSet<Permissions> Permissions { get; set; }
        public DbSet<RolePermissions> RolePermissions { get; set; }
        public DbSet<Roles> Roles { get; set; }
        public DbSet<UserRoles> UserRoles { get; set; }
        public DbSet<Users> Users { get; set; }
        public DbSet<Approvals> Approvals { get; set; }

        public override int SaveChanges()
        {
            OnSavingChanges();
            return base.SaveChanges();
        }
        public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
        {
            OnSavingChanges();
            return base.SaveChangesAsync(cancellationToken);
        }
        private void OnSavingChanges()
        {
            foreach (var entry in ChangeTracker.Entries())
            {
                if (entry.Entity is BaseEneity baseEntity && entry.State == EntityState.Deleted)
                {
                    // 取消删除操作
                    entry.State = EntityState.Modified;

                    // 设置软删除标记
                    baseEntity.IsDeleted = true;
                    baseEntity.DelDate = DateTime.Now;

                    // 可选：记录删除用户
                    // baseEntity.DeletedBy = _currentUserService.UserId;
                }
            }
        }
    }
}
